package com.sezi.blog.service.impl;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.sezi.blog.service.IBaseService;
import com.sezi.vo.page.DataPageVo;
import com.sezi.vo.page.Order.Direction;

@Component
public class BaseServiceImpl<T> implements IBaseService<T>{

	private static final Logger logger = Logger.getLogger(BaseServiceImpl.class);
	
	@PersistenceContext
	protected EntityManager entityManager;
	
	@SuppressWarnings("unchecked")
	public Class<T> getGenericType() {
	  Type genType = getClass().getGenericSuperclass();
//	  if (!(genType instanceof ParameterizedType)) {
//	   return Object.class;
//	  }
	  Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
//	  if (!(params[0] instanceof Class)) {
//	   return Object.class;
//	  }
	  return (Class<T>) params[0];
	}
	
	
	@Override
	public T findOne(Long id) {
		return (T)entityManager.find(getGenericType(), id);
	}

	@Override
	public List<T> findAll(DataPageVo vo) {
		StringBuilder HQL = new StringBuilder("FROM ")
							.append(getGenericType().getSimpleName())
							.append(" where ")
							.append(vo.getSearchParam())
							.append(" like %?%")
							.append(" order by ? ");
		try{
			Direction dir = Direction.valueOf(vo.getOrder());
			HQL.append(dir.toString());
		}catch(Exception e){
			HQL.append("ASC");
			logger.info("设置排序出错",e);
		}
		Query query = entityManager.createQuery(HQL.toString(), getGenericType());
		query.setMaxResults(vo.getPageSize())
		     .setFirstResult((vo.getPageNo()-1)*vo.getPageSize());
		query.setParameter(1, vo.getSearchParam());
		query.setParameter(2, vo.getOrder());
		@SuppressWarnings("unchecked")
		List<T> list = (List<T>)query.getResultList();
		return list;
	}

	@Override
	public T save(T entity) {
		try{
			entityManager.persist(entity);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("持久化对象出错",e);
			return null;
		}
		return entity;
	}

	@Override
	public T update(T entity) {
		try{
			entityManager.merge(entity);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("更新对象出错",e);
			return null;
		}
		return entity;
	}

	@Override
	public boolean delete(Long id) {
		try{
			entityManager.remove(findOne(id));
		}catch(Exception e){
			e.printStackTrace();
			logger.error("删除对象出错",e);
			return false;
		}
		return true;
	}

	@Override
	public boolean delete(T entity) {
		try{
			entityManager.remove(entity);
		}catch(Exception e){
			e.printStackTrace();
			logger.error("删除对象出错",e);
			return false;
		}
		return true;
	}

	
	@SuppressWarnings("unchecked")
	@Override
	public List<T> findAll() {
		return (List<T>)entityManager.createQuery("FROM "+getGenericType().getSimpleName()).getResultList();
	}

}
